package com.caidan.search.utils;

import com.caidan.search.config.MinioConstantProperties;
import io.minio.*;
import io.minio.errors.MinioException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @项目名 tingshu-parent
 * @描述 封装Minio上传文件方法
 * @作者 小菜蛋
 * @时间 2024/11/26 20:21
 */

@Component
@Slf4j
public class MinioUploadFileUtils implements InitializingBean {

    @Resource
    private MinioConstantProperties minioConstantProperties;
    public MinioClient minioClient = null;
    /***
     * 上传文件
     * @param fileName
     * @param file
     * @return
     */
    public String uploadFile(String fileName, MultipartFile file) {
        if (null == file) {
            log.info("[upload] params file is null , file use default to replace");
//            设置一个默认图片
            return "default";
        }
        if (null == fileName) {
            log.info("[upload] params fileName is null , fileName use uuid to replace");
            fileName = UUID.randomUUID().toString().replace("-", "");
        }
        String url = "";
        try {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConstantProperties.getBucketName())
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            url = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + fileName;
            log.info("file upload successful");
            return url;
        } catch (Exception e) {
            log.error("[uploadFile] is error , error message is {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * 删除文件
     * @param fileUrl
     * @return
     */
    /*
        当我们更新的时候可以调用删除，将原本的信息删除掉。
        文件上传的时候出现多次上传，可以在前端进行限制，只缓存，但是不上传，只有点击上传的时候再上传。
     */
    public boolean remove(String fileUrl) {
        try {
            String fileName = fileUrl.substring(fileUrl.lastIndexOf('.') + 1, -1);
            // 调用 MinioClient 的 removeObject 方法删除文件
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(minioConstantProperties.getBucketName())
                            .object(fileName)
                            .build()
            );
            return true; // 删除成功
        } catch (Exception e) {
            log.error("Failed to remove file: Error: " + e.getMessage());
            return false; // 删除失败
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
//        链接minio
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConstantProperties.getEndpointUrl())
                    .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                    .build();
            boolean found =
                    minioClient
                            .bucketExists(
                                    BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
//                桶不存在 重新创建
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            } else {
                log.error("Bucket {} already exists.", minioConstantProperties.getBucketName());
            }
//            更新
            this.minioClient = minioClient;
//            上传代码
        } catch (MinioException e) {
            log.error("[MinioUploadFileUtils.afterPropertiesSet] is error , error message is {}", e.getMessage());
        }
    }
}
